package com.example.common.component;


import android.util.Log;

import com.example.common.control.ICallback;
import com.example.common.model.MyResponse;
import com.example.common.network.FileReq;
import com.example.common.network.RetrofitServiceManager;

import java.io.File;
import java.net.URL;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FileCtrlCom {
    private FileReq fileReq;

    public FileCtrlCom(){
        fileReq= RetrofitServiceManager.getInstance().create(FileReq.class);
    }

    public void upLoadImg(String path,String token, ICallback iCallback){
        //通过链接获取图片文件
        File file=new File(path);
        Log.i("TAG", "upLoadImg: "+file.getName());

        //创建请求体
        MultipartBody.Builder builder=new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        RequestBody fileRQ=RequestBody.create(MediaType.parse("multipart/form-data"),file);
//        MultipartBody.Part body=MultipartBody.Part.createFormData("file",file.getName(),fileRQ);
        builder.addFormDataPart("file",file.getName(),fileRQ);
        //创建请求
        Call<MyResponse<String>> call=fileReq.uploadFile(builder.build().part(0),token);
        //发出请求
        call.enqueue(new Callback<MyResponse<String>>() {
            @Override
            public void onResponse(Call<MyResponse<String>> call, Response<MyResponse<String>> response) {
                if(response.isSuccessful()){
                    if (response.body()!=null){
                        MyResponse<String> myResponse= response.body();
                        if(myResponse.getCode()==200){
                            //返回值为String
                            Log.i("TAG", "onResponse: 上传文件成功！");
                            iCallback.onSuccess(myResponse.getData());
                        }else {
                            iCallback.onFailed(myResponse.getErrmsg());
                        }
                    }else {
                        iCallback.onFailed("返回为空");
                    }
                }else {
                    iCallback.onFailed("网络错误");
                }
            }

            @Override
            public void onFailure(Call<MyResponse<String>> call, Throwable t) {
                iCallback.onFailed(call.toString());
            }
        });
    }
}
